package com.company;

import java.util.concurrent.*;

class CallAbleTask implements Callable<Object>{
    @Override
    public Object call() throws Exception {
        Thread.sleep(2000);
        return 100;
    }
}

public class TestFutureThread {
    public static void test(){
        ExecutorService pool = Executors.newFixedThreadPool(4);
        Callable<Object> cb = new CallAbleTask();
        Future fu = pool.submit(cb);
        try {
            System.out.println(fu.get(3,TimeUnit.SECONDS));
            System.out.println("future get over");
        } catch (TimeoutException | InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }

    //CompletableFuture 提供异步回调解决方案
    public static void testCompletable() throws InterruptedException {
        asynDo();
        Thread.sleep(200);
    }

      public static void testCompletable2(){
        Thread th = new Thread(()->{
            try {
                asynDo();

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return;
        });

        th.start();
      }

    private static void asynDo() throws InterruptedException {
        CompletableFuture<Double> cf = CompletableFuture.supplyAsync(()->{
            try {
                Thread.sleep(100);
                if(Math.random() > 0.5){
                    throw new RuntimeException("fail");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return  Math.random()*20;
        });
        cf.thenAccept((result)->{
            System.out.println("result:"+result);
        });
        cf.exceptionally((e)->{
            e.printStackTrace();
            return null;
        });
        System.out.println("last");

    }
}
